package com.miracle.main.module.mvp.ui.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.laojiang.imagepickers.ImagePicker;
import com.laojiang.imagepickers.data.ImageContants;
import com.laojiang.imagepickers.data.ImagePickType;
import com.laojiang.imagepickers.data.MediaDataBean;
import com.miracle.basemvp.base.BaseActivity;
import com.miracle.basemvp.base.BaseFragment;
import com.miracle.basemvp.di.component.AppComponent;
import com.miracle.basemvp.network.download.ProgressDownloadListener;
import com.miracle.basemvp.network.glide.GlideApp;
import com.miracle.basemvp.util.FileUtils;
import com.miracle.common.state.user.LogOutState;
import com.miracle.common.state.user.LoginContext;
import com.miracle.common.util.CommonConstants;
import com.miracle.common.util.GlideCircleTransform;
import com.miracle.common.util.ImageUtil;
import com.miracle.common.util.PreferencesUtils;
import com.miracle.common.util.S;
import com.miracle.common.util.VersionUtil;
import com.miracle.common.view.BaseDialogProvider;
import com.miracle.main.R;
import com.miracle.main.R2;
import com.miracle.main.module.di.component.DaggerSettingComponent;
import com.miracle.main.module.di.module.SettingModule;
import com.miracle.main.module.mvp.contract.SettingContract;
import com.miracle.main.module.mvp.presenter.SettingPresenter;
import com.miracle.main.module.mvp.ui.activity.UpdateInfoActivity;
import com.miracle.main.util.PhotoSelectPopup;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static com.miracle.main.MainConstants.UPDATE_TYPE.TYPE_MAIL;
import static com.miracle.main.MainConstants.UPDATE_TYPE.TYPE_NAME;
import static com.miracle.main.MainConstants.UPDATE_TYPE.TYPE_PWD;
import static com.miracle.main.MainConstants.UPDATE_TYPE.TYPE_TEL;

/**
 * com.miracle.main.module.mvp.ui.fragment
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/2 18:14
 * @see com.miracle.main.module.mvp.ui.fragment
 */
public class SettingFragment extends BaseFragment<SettingPresenter> implements SettingContract
        .View, View.OnClickListener, ProgressDownloadListener {
    private static final int TAG_UPDATE = 1;
    private static final int TAG_EXIT = 2;


    @BindView(R2.id.iv_exit)
    ImageView mIvLogOut;
    @BindView(R2.id.iv_has_newversion)
    ImageView mIvHasNewVersion;
    @BindView(R2.id.tv_name)
    TextView mTvName;
    @BindView(R2.id.tv_sex)
    TextView mTvSex;
    @BindView(R2.id.tv_tel)
    TextView mTvTel;
    @BindView(R2.id.tv_mail)
    TextView mTvMail;
    @BindView(R2.id.tv_version)
    TextView mTvVersion;
    @BindView(R2.id.ll_name)
    RelativeLayout mRLName;
    @BindView(R2.id.v_popup)
    View mView;

    LifecycleProvider<FragmentEvent> lifecycleProvider;

    @Override
    public int setLayoutId(@Nullable Bundle bundle) {
        return R.layout.cloud_fragment_setting;
    }

    @Override
    public void setDaggerComponent(AppComponent appComponent) {
        DaggerSettingComponent
                .builder()
                .appComponent(appComponent)
                .settingModule(new SettingModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void init(@Nullable Bundle bundle) {
    }

    @Override
    public void initView() {
        //用户名
        String name = PreferencesUtils.getPreferences(mContext, PreferencesUtils.State.USER_NAME);
        String sex = PreferencesUtils.getPreferences(mContext, PreferencesUtils.State.USER_SEX);
        String tel = PreferencesUtils.getPreferences(mContext, PreferencesUtils.State.USER_TEL);
        String mail = PreferencesUtils.getPreferences(mContext, PreferencesUtils.State.USER_MAIL);
        if (TextUtils.isEmpty(name)) {
            mRLName.setVisibility(View.GONE);
        } else {
            mRLName.setVisibility(View.VISIBLE);
        }
        mTvName.setText(name);
        //性别
        mTvSex.setText(CommonConstants.Sex.getValues(sex));
        //电话
        mTvTel.setText(tel);
        //邮箱
        mTvMail.setText(mail);
        //版本名称
        String versionName = VersionUtil.getLocalVersionName(mContext);
        mTvVersion.setText(versionName);
    }

    @Override
    public void initData() {
        checkVersion();
    }

    private void checkVersion() {
        int currVersion = VersionUtil.getLocalVersion(mContext);
        int newestVersion = PreferencesUtils.getIntPreferences(mContext, PreferencesUtils.Version
                .VERSION_NEWEST);
        if (currVersion < newestVersion) {
            mIvHasNewVersion.setVisibility(View.VISIBLE);
        } else {
            mIvHasNewVersion.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequest(LifecycleProvider<FragmentEvent> lifecycleProvider) {
        this.lifecycleProvider = lifecycleProvider;
    }

    @Override
    public void showData(Object o) {

    }

    BaseDialogProvider mUpdateDialogProvider;
    AlertDialog mUpdateDialog;

    public void showUpdateDialog(String msg) {
        if (mUpdateDialog == null) {
            mUpdateDialogProvider = new BaseDialogProvider(mContext);
            mUpdateDialog = mUpdateDialogProvider.createDialog(R.layout
                    .dialog_common_mention_single_message);
        }
        ((TextView) mUpdateDialogProvider.getView(R.id.tv_title)).setText("检查更新");
        ((TextView) mUpdateDialogProvider.getView(R.id.tv_dialog_message)).setText(msg);
        mUpdateDialogProvider.getView(R.id.tv_dialog_cancel).setOnClickListener(this);
        TextView tvOk = mUpdateDialogProvider.getView(R.id.tv_dialog_ok);
        tvOk.setTag(TAG_UPDATE);
        tvOk.setOnClickListener(this);
        mUpdateDialog.show();
    }


    BaseDialogProvider mExitDialogProvider;
    AlertDialog mExitDialog;

    public void showExitDialog() {
        if (mExitDialog == null) {
            mExitDialogProvider = new BaseDialogProvider(mContext);
            mExitDialog = mExitDialogProvider.createDialog(R.layout
                    .dialog_common_mention_single_message);
        }
        ((TextView) mExitDialogProvider.getView(R.id.tv_title)).setText("退出登陆");
        ((TextView) mExitDialogProvider.getView(R.id.tv_dialog_message)).setText("是否要退出登陆?");
        mExitDialogProvider.getView(R.id.tv_dialog_cancel).setOnClickListener(this);
        TextView tvOk = mExitDialogProvider.getView(R.id.tv_dialog_ok);
        tvOk.setTag(TAG_EXIT);
        tvOk.setOnClickListener(this);
        mExitDialog.show();
    }


    BaseDialogProvider mProgressProvider;
    AlertDialog mProgressDialog;
    ProgressBar mDownloadProgress;

    /**
     * 下载进度dialog
     */
    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressProvider = new BaseDialogProvider(mContext);
            mProgressDialog = mProgressProvider.createDialog(R.layout
                    .dialog_common_progress);
        }
        ((TextView) mProgressProvider.getView(R.id.tv_title)).setText("下载进度");
        mDownloadProgress = mProgressProvider.getView(R.id.dialog_progress);
        mProgressProvider.getView(R.id.tv_dialog_cancel).setOnClickListener(this);
        TextView tvOk = mProgressProvider.getView(R.id.tv_dialog_ok);
        tvOk.setTag(TAG_EXIT);
        tvOk.setOnClickListener(this);
        mProgressDialog.show();
    }

    @Override
    public void FindANewVersion(String msg) {
        checkVersion();
        showUpdateDialog(msg);
    }

    @Override
    public void NoNewVersion() {
        S.Short(mIvLogOut, "已经是最新版本").info().show();
    }

    public void requestPermission() {
        RxPermissions rxPermission = new RxPermissions(mActivity);
        rxPermission
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mPresenter.downloadApk(lifecycleProvider, "", SettingFragment.this);
                        } else {
                        }
                    }
                });
    }


    @OnClick({R2.id.fl_update, R2.id.iv_exit, R2.id.ll_name, R2.id.ll_sex, R2.id.ll_tel, R2.id
            .ll_mail, R2.id.ll_pwd, R2.id.civ_head})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.fl_update) {
            //show loading dialog
            mPresenter.checkVersion(lifecycleProvider);
        }

        if (id == R.id.iv_exit) {
            showExitDialog();
        }
        //修改信息
        if (id == R.id.ll_name) {
            UpdateInfoActivity.start((BaseActivity) mActivity, TYPE_NAME);
        }
        if (id == R.id.ll_sex) {
            UpdateInfoActivity.start((BaseActivity) mActivity, TYPE_NAME);
        }
        if (id == R.id.ll_tel) {
            UpdateInfoActivity.start((BaseActivity) mActivity, TYPE_TEL);
        }
        if (id == R.id.ll_pwd) {
            UpdateInfoActivity.start((BaseActivity) mActivity, TYPE_PWD);
        }
        if (id == R.id.ll_mail) {
            UpdateInfoActivity.start((BaseActivity) mActivity, TYPE_MAIL);
        }

        if (id == R.id.civ_head) {
            showPicAddMethodDialog();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_dialog_cancel) {
            //隐藏更新提示dialog
            if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
                mUpdateDialog.dismiss();
            }
            if (mExitDialog != null && mExitDialog.isShowing()) {
                mExitDialog.dismiss();
            }
        }

        if (id == R.id.tv_dialog_ok) {
            int tag = (int) v.getTag();
            if (tag == TAG_UPDATE) {
                //隐藏更新提示dialog
                if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
                    mUpdateDialog.dismiss();
                }
                showProgressDialog();
                requestPermission();
            } else if (tag == TAG_EXIT) {
                if (mExitDialog != null && mExitDialog.isShowing()) {
                    mExitDialog.dismiss();
                }
                LoginContext.getLoginContext().setUserState(mContext, new LogOutState());
                LoginContext.getLoginContext().setUser(mContext, null);
                getActivity().finish();
            }
        }

        //图片添加dialog
        if (id == R.id.ll_pic) {
            if (mAddPicMethodDialog != null) {
                mAddPicMethodDialog.dismiss();
            }
            ImageUtil.getSinglePic(this, ImagePickType.SINGLE, REQUEST_CODE_PIC, RESULT_CODE_PIC);
        }
        //相机添加
        if (id == R.id.ll_camera) {
            ImageUtil.getSinglePic(this, ImagePickType.ONLY_CAMERA, 100, 200);
            if (mAddPicMethodDialog != null) {
                mAddPicMethodDialog.dismiss();
            }
        }
    }

    BaseDialogProvider dialogProvider;
    AlertDialog mAddPicMethodDialog;

    /**
     * “请选择图片添加方式”Dialog
     */
    private void showPicAddMethodDialog() {
        if (mAddPicMethodDialog == null) {
            dialogProvider = new BaseDialogProvider(mContext);
            mAddPicMethodDialog = dialogProvider.createDialog(R.layout
                    .dialog_add_pic_style);
        }
        dialogProvider.getView(R.id.ll_pic).setOnClickListener(this);
        dialogProvider.getView(R.id.ll_camera).setOnClickListener(this);
        mAddPicMethodDialog.show();
    }

    @Override
    public void onStartDownload() {
        S.Short(mIvLogOut, "onStartDownload").warning().show();
        Log.d("WJQ", "onStartDownload");
    }

    @Override
    public void onProgress(int i) {
        Log.d("WJQ", "onProgress");
        if (mDownloadProgress != null && i > 0) {
            mDownloadProgress.setProgress(i);
        }
    }

    @Override
    public void onFinishDownload() {
        S.Short(mIvLogOut, "onFinishDownload").warning().show();
        Log.d("WJQ", "onFinishDownload");
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        String filePath = Environment.getExternalStorageDirectory() + "/WeCloud/wecloud.apk";
        String provider = "com.miracle.cloud.fileprovider";
        FileUtils.installApk(mContext, filePath, provider);
    }

    @Override
    public void onFail(String s) {
        S.Short(mIvLogOut, "onFail: " + s).warning().show();
        Log.d("WJQ", "onFail");
    }

    public static final int REQUEST_CODE_PIC = 100;
    public static final int RESULT_CODE_PIC = 101;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PIC && resultCode == RESULT_CODE_PIC) {
            List<MediaDataBean> resultList = data.getParcelableArrayListExtra(ImagePicker
                    .INTENT_RESULT_DATA);
            if (resultList != null && resultList.size() > 0) {
                mPresenter.uploadFiles(lifecycleProvider,resultList.get(0).getMediaPath());
            }
        }

        if (requestCode == ImageContants.CAMERA_REQUEST && data != null) {
            String path = data.getStringExtra(ImageContants.DIY_CAMERA_PATH);

        }
    }
}
